package com.example.carddemo;

import com.example.carddemo.slice.MainAbilitySlice;
import com.example.carddemo.widget.controller.*;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.FormException;
import ohos.aafwk.ability.ProviderFormInfo;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentProvider;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.zson.ZSONObject;

import java.util.Map;

public class MainAbility extends Ability {
    public static final int DEFAULT_DIMENSION_2X2 = 2; //System-defined constant. Do not change its value.
    private static final int INVALID_FORM_ID = -1;
    private static final HiLogLabel TAG = new HiLogLabel(HiLog.DEBUG, 0x0, MainAbility.class.getName());
    private String topWidgetSlice;

    public long formId = -1;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
        formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, -1);
    }

    @Override
    protected ProviderFormInfo onCreateForm(Intent intent) {
        HiLog.info(TAG, "onCreateForm");
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        String formName = intent.getStringParam(AbilitySlice.PARAM_FORM_NAME_KEY);
        int dimension = intent.getIntParam(AbilitySlice.PARAM_FORM_DIMENSION_KEY, DEFAULT_DIMENSION_2X2);
        HiLog.info(TAG, "onCreateForm: formId=" + formId + ",formName=" + formName);
        ProviderFormInfo formInfo = new ProviderFormInfo(ResourceTable.Layout_form_image_with_info_widget_2_2, this);
        createFormToSave(formId, formName, dimension);
        ComponentProvider componentProvider = formInfo.getComponentProvider();
        componentProvider.setText(ResourceTable.Id_widget_titlt_text, "自定义卡片标题");
        componentProvider.setText(ResourceTable.Id_widget_titlt_desc, "自定义卡片描述文案");
        formInfo.mergeActions(componentProvider);
        return formInfo;
    }

    @Override
    protected void onUpdateForm(long formId) {
        super.onUpdateForm(formId);
        ComponentProvider componentProvider = new ComponentProvider(ResourceTable.Layout_form_image_with_info_widget_2_2, this);
        // 获取卡片实例需要更新的卡片数据，对卡片进行更新
        ZSONObject object = getForm(formId);
        componentProvider.setText(ResourceTable.Id_widget_titlt_desc, "更新后的描述文案");
        try {
            // 调用yodateForm方法来刷新服务卡片
            updateForm(formId, componentProvider);
        } catch (FormException e) {
            e.printStackTrace();
        }
    }

    public ZSONObject getForm(long formId) {
        // 数据库帮助类实例
        DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
        // 获取Preferences实例
        Preferences preferences = databaseHelper.getPreferences("form_info_sp");
        // 获取存储的所有卡片数据
        Map<String, ?> forms = preferences.getAll();
        String formIdString = Long.toString(formId);
        // 读取JSON对象返回
        return ZSONObject.stringToZSON((String) forms.get(formIdString));
    }

    public void createFormToSave(long formId, String formName, int dimension) {
        // 数据有效性判断
        if (formId < 0 || formName.isEmpty()) {
            return;
        }
        // 数据库帮助类实例
        DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
        // 获取Preferences实例
        Preferences preferences = databaseHelper.getPreferences("form_info_sp");
        if (preferences != null) {
            // 定义JSON对象进行存储
            ZSONObject formObj = new ZSONObject();
            formObj.put("name", formName);
            formObj.put("type", dimension);
            preferences.putString(Long.toString(formId), ZSONObject.toZSONString(formObj));
            preferences.flushSync();
        }
    }

    @Override
    protected void onDeleteForm(long formId) {
        super.onDeleteForm(formId);
        deleteForm(formId);
    }

    public void deleteForm(long formId) {
        // 数据库帮助类实例
        DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext());
        // 获取Preferences实例
        Preferences preferences = databaseHelper.getPreferences("form_info_sp");
        preferences.delete(Long.toString(formId));
        preferences.flushSync();
    }

    @Override
    protected void onTriggerFormEvent(long formId, String message) {
        HiLog.info(TAG, "onTriggerFormEvent: " + message);
        super.onTriggerFormEvent(formId, message);
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        formController.onTriggerFormEvent(formId, message);
    }

    private boolean intentFromWidget(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, -1);
        return formId != INVALID_FORM_ID;
    }

    private String getRoutePageSlice(Intent intent) {
        long formId = intent.getLongParam(AbilitySlice.PARAM_FORM_IDENTITY_KEY, INVALID_FORM_ID);
        if (formId == INVALID_FORM_ID) {
            return null;
        }
        FormControllerManager formControllerManager = FormControllerManager.getInstance(this);
        FormController formController = formControllerManager.getController(formId);
        if (formController == null) {
            return null;
        }
        Class<? extends AbilitySlice> clazz = formController.getRoutePageSlice(intent);
        if (clazz == null) {
            return null;
        }
        return clazz.getName();
    }

    @Override
    public void onNewIntent(Intent intent) {
        if (intentFromWidget(intent)) { // Only response to it when starting from a service widget.
            String newWidgetSlice = getRoutePageSlice(intent);
            if (topWidgetSlice == null || !topWidgetSlice.equals(newWidgetSlice)) {
                topWidgetSlice = newWidgetSlice;
                restart();
            }
        } else {
            if (topWidgetSlice != null) {
                topWidgetSlice = null;
                restart();
            }
        }
    }
}
